package com.genghis.rapidcrm.web.interceptor;

import com.genghis.rapidcrm.web.view.RapidActionView;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xulixin
 */
@Component
public class RapidViewInterceptor implements HandlerInterceptor {

    @Value("${spring.freemarker.expose-request-attributes}")
    private String exposeRequestAttributes;
    @Value("${spring.freemarker.expose-session-attributes}")
    private String exposeSessionAttributes;
    @Value("${spring.freemarker.expose-spring-macro-helpers:true}")
    private String exposeSpringMacroHelpers;

    @Value("${spring.freemarker.charset}")
    private String charset = "utf8";

    @Value("${spring.freemarker.content-type}")
    private String contentType = "";

    private final ApplicationContext applicationContext;

    public RapidViewInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView mav)
            throws Exception {

        if (mav == null) {
            return;
        }
        if (mav.getView() instanceof RapidActionView) {
            RapidActionView view = (RapidActionView) mav.getView();
            view.setApplicationContext(this.applicationContext);
            view.setExposeRequestAttributes(false);
            view.setExposeSessionAttributes(false);
            view.setExposeSpringMacroHelpers(false);
            view.setContentType(contentType + ";charset=" + charset);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex)
            throws Exception {

    }
}
